/*
 * Copyright (c) 2012 Acorn International.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http:www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or  implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package com.chinadrtv.batch.admin.filter;

import com.chinadrtv.user.model.Role;
import com.chinadrtv.user.model.User;
import com.chinadrtv.user.model.ozing.auth.OzingUser;
import com.chinadrtv.user.service.ozing.IAuthService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Set;


/**
 * User: Jack.Chen
 * Date: 12-9-3
 * Record login time as  user login successfully
 */
public class RedirectAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
    private final Log logger = LogFactory.getLog(RedirectAuthenticationSuccessHandler.class);
    @Autowired
    private IAuthService authManager;
    /**
     * 如果是ROLE_OZING_AGENT 角色的用户，跳转到/agent/salesterminal地址
     *
     * @param request
     * @param response
     * @param authentication
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response, Authentication authentication)
            throws IOException, ServletException {

        User user = (User) authentication.getPrincipal();
        if (user == null) {
            return;
        }
        // add auth 2013/05/13
        OzingUser ozingUser = authManager.findByUser(user);
        request.getSession().setAttribute(OzingUser.OZING_USER_SESSION_KEY, ozingUser);

        super.setAlwaysUseDefaultTargetUrl(true);

        Set<Role> roles = user.getRoles();
        boolean isAgentUser = false;
        for (Role role : roles) {
            if (role.getName().equals("ROLE_OZING_AGENT") || role.getName().equals("ROLE_AGENT_ADMIN")) {
                isAgentUser = true;
            }
        }

        super.setAlwaysUseDefaultTargetUrl(true);
        if (isAgentUser) {
            setDefaultTargetUrl("/agent/salesterminal");
        } else {
            // update by troy: 额外的权限控制
            if (ozingUser != null && ozingUser.getRoles() != null && ozingUser.getRoles().size() > 0) {
                String any = ozingUser.hasAnyAuth();
                if (ozingUser.hasAnyAuth() != null) {
                    setDefaultTargetUrl(any);
                } else {
                    setDefaultTargetUrl("/ozing/card/job");
                }
            }
        }


        super.onAuthenticationSuccess(request, response, authentication);
    }

}

